package com.ld.common.util.filelistener.commonio.impl;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.monitor.FileAlterationObserver;

import com.ld.admin.model.system.NoticeActionModel;
import com.ld.admin.model.system.filelistener.SysFilelistenerChlogModel;
import com.ld.admin.model.system.filelistener.SysFilelistenerModel;
import com.ld.admin.service.system.filelistener.SysFileLinstenerService;
import com.ld.common.util.filelistener.FileChangeModel;
import com.ld.common.util.notice.NoticeUtil;
import com.ld.shieldsb.common.core.util.DateUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.util.server.WebServerUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
/**
 * 项目使用的文件变化处理器(注意此类异常不可抛出)，
 * 
 * @ClassName FileChangedListener
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年1月17日 下午5:04:56
 *
 */
public class ProjectFileChangedHandler extends AbstractChangedHandler {
    protected static SysFileLinstenerService service = new SysFileLinstenerService();
    private SysFilelistenerModel model = null;

    public ProjectFileChangedHandler(SysFilelistenerModel model, NoticeActionModel noticActionModel) {
        super(noticActionModel);
        this.model = model;
    }

    /**
     * File system observer started checking event.
     */
    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
    }

    /**
     * File system observer finished checking event.
     */
    @Override
    public void onStop(FileAlterationObserver observer) {
        super.onStop(observer);
        if (changedFiles.size() == lastChangedSize && lastChangedSize > 0) { // 不再发生变化时发送通知
            // 发送通知
            if (noticActionModel != null && StringUtils.isNotBlank(noticActionModel.getType())) {
                String content = "共有" + changedFiles.size() + "个文件发生变化：\r\n";
                for (FileChangeModel file : changedFiles) {
                    content += file.getRemarks() + " : " + file.getChangedFile().getName() + "(" + file.getChangedFile().getParent()
                            + ")\r\n";
                }
                try {
                    NoticeUtil.sendNotice(noticActionModel, content);
                } catch (Exception e) {
                    log.error("文件监控发送通知失败", e);
                }
            }
//    EmailInfo mailInfo = new EmailInfo();
//    String sendTo = "291490365@qq.com";
//    mailInfo.addToAddress(sendTo);
//    mailInfo.setSubject("检测到文件变化");
//    mailInfo.setContent(content);
            //
//    EmailUtil.sendEmail(mailInfo).getSuccess();
            changedFiles.clear(); // 清空重新处理
            lastChangedSize = 0;
        } else {
            lastChangedSize = changedFiles.size();
        }
    }

    /**
     * Directory created Event.
     */
    @Override
    public void onDirectoryCreate(File directory) {
        super.onDirectoryCreate(directory);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(directory);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(directory.lastModified())) + "]目录创建");
        changedFiles.add(changedModel);
        recordFileChangeLog(model, directory, "目录创建");
    }

    /**
     * Directory changed Event
     */
    @Override
    public void onDirectoryChange(File directory) {
        super.onDirectoryChange(directory);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(directory);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(directory.lastModified())) + "]目录修改");
        // 不记录了，目录修改里面的文件也会修改
        // changedFiles.add(changedModel);
        // recordFileChangeLog(model, directory, "目录修改");
    }

    /**
     * Directory deleted Event.
     */
    @Override
    public void onDirectoryDelete(File directory) {
        super.onDirectoryDelete(directory);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(directory);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(directory.lastModified())) + "]目录删除");
        changedFiles.add(changedModel);
        recordFileChangeLog(model, directory, "目录删除");
    }

    /**
     * File created Event.
     */
    @Override
    public void onFileCreate(File file) {
        super.onFileCreate(file);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(file);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(file.lastModified())) + "]文件创建");
        changedFiles.add(changedModel);
        recordFileChangeLog(model, file, "文件创建");

    }

    /**
     * File changed Event.
     */
    @Override
    public void onFileChange(File file) {
        super.onFileChange(file);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(file);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(file.lastModified())) + "]文件修改");
        changedFiles.add(changedModel);
        recordFileChangeLog(model, file, "文件修改");
    }

    /**
     * File deleted Event.
     */
    @Override
    public void onFileDelete(File file) {
        super.onFileDelete(file);
        FileChangeModel changedModel = new FileChangeModel();
        changedModel.setChangedFile(file);
        changedModel.setRemarks("[" + DateUtil.getDateTimeString(new Date(file.lastModified())) + "]文件删除");
        changedFiles.add(changedModel);
        recordFileChangeLog(model, file, "文件删除");
    }

    /**
     * 记录变化文件到数据库中
     * 
     * @Title recordFileChangeLog
     * @author 吕凯
     * @date 2019年1月29日 下午2:21:44
     * @param model
     * @param file
     * @param event
     *            void
     */
    private void recordFileChangeLog(SysFilelistenerModel model, File file, String event) {
        SysFilelistenerChlogModel logModel = new SysFilelistenerChlogModel();
//        logModel.setBatchNo(DateUtil.getDateString(new Date()) + "-" + StringUtils.getRandomStr(4)); // 批次号
        logModel.setEvent(event);
        logModel.setFlistenerId(model.getId());
        logModel.setFileName(file.getName());
        logModel.setFilePath(file.getAbsolutePath());
        logModel.setFilesize(file.length());
        Date lastModifiedTime = new Date(file.lastModified());
        log.warn(file.lastModified() + "");
        if (file.lastModified() == 0) { // 删除时
            lastModifiedTime = new Date();
        }
        logModel.setFileUpdateTime(lastModifiedTime);
        logModel.setServerIp(WebServerUtil.getHost());
        service.getBaseDAO().save(logModel);
    }

    public SysFilelistenerModel getModel() {
        return model;
    }

    public void setModel(SysFilelistenerModel model) {
        this.model = model;
    }

    public NoticeActionModel getNoticeActionModel() {
        return noticActionModel;
    }

    public void setNoticeActionModel(NoticeActionModel noticActionModel) {
        this.noticActionModel = noticActionModel;
    }

}
